import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_prompt_overlay.dart';
import 'package:interview/components/page/page_menu_item.dart';
import 'package:interview/components/page/page_menu_overlay.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/controller/interview_details_controller.dart';
import 'package:interview/controller/question_details_controller.dart';
import 'package:interview/pages/question/components/question_answer.dart';
import 'package:interview/pages/question/components/question_footer.dart';
import 'package:interview/pages/question/components/question_userinfo.dart';
import 'package:interview/pages/question/components/share_overlay.dart';
import 'package:interview/servers/question_detail.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/services.dart' show rootBundle; // 用于加载本地文件

class QuestionContent extends StatefulWidget {
  final int typeId; // 频道id
  final String? tab; // 面经tab
  final QuestionDetail questionDetail; // 题目信息
  final AppColors theme; // 主题样式
  final List<String>? ids; // 分享时需要用到

  const QuestionContent({
    required this.questionDetail,
    required this.theme,
    required this.typeId,
    this.tab,
    this.ids,
  });

  @override
  _QuestionContentState createState() => _QuestionContentState();
}

class _QuestionContentState extends State<QuestionContent> {
  final QuestionDetailsController _questionDetailsController = Get.find<QuestionDetailsController>();
  final InterviewDetailsController _interviewDetailsController = Get.find<InterviewDetailsController>();

  late WebViewController _controller; // WebView控制器
  bool _isHtmlLoaded = false; // 标记HTML是否已加载
  @override
  void initState() {
    super.initState();
    _initializeWebView();
  }

  @override
  void dispose() {
    super.dispose();
    PageMenuOverlay.hide();
  }

  Future<void> _initializeWebView() async {
    Logger.info("${widget.questionDetail.answer}" , tag: "_initializeWebView");
    _controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted);
    await _loadLocalHtml();
    // 设置 NavigationDelegate
    _controller.setNavigationDelegate(
      NavigationDelegate(
        onPageStarted: (String url) {},
        onPageFinished: (String url) async {
          await _renderAnswer(widget.questionDetail.answer.isEmpty? widget.questionDetail.content : widget.questionDetail.answer );
        },
        onWebResourceError: (WebResourceError error) {
          Logger.error("网页资源错误: ${error.description}", tag: 'onWebResourceError');
        },
      ),
    );
  }

  Future<void> _loadLocalHtml() async {
    try {
      // 从 assets 加载本地 HTML 文件内容
      String htmlTemplate = await rootBundle.loadString('${AppEnumAssets.rawfilePath}question.html');
      final css = await rootBundle.loadString('${AppEnumAssets.rawfilePath}github.min.css');
      final js = await rootBundle.loadString('${AppEnumAssets.rawfilePath}highlight.min.js');
      htmlTemplate = htmlTemplate
        .replaceFirst('<link rel="stylesheet" href="./github.min.css">', '<style>$css</style>')
        .replaceFirst('<script src="./highlight.min.js"></script>', '<script>$js</script>');
      await _controller.loadHtmlString(htmlTemplate);
    } catch (e) {
      debugPrint("加载本地HTML文件失败: $e");
    }
  }

  Future<void> _renderAnswer(String answer) async {
    try {
      final escapedAnswer = _escapeAndFormatAnswer(answer);
      final jsCode = "writeHtml(`$escapedAnswer`)";
      await _controller.runJavaScript(jsCode);
      setState(() {
        _isHtmlLoaded = true;
      });
    } catch (e) {
      Logger.error("渲染失败 $e", tag: "_renderAnswer");
    }
  }

  String _escapeAndFormatAnswer(String answer) {
    return answer
      .replaceAll(r'\', r'\\\\')  // 转义反斜杠
      .replaceAll('"', r'\"')    // 转义双引号
      .replaceAll("'", r"\'")    // 转义单引号
      .replaceAllMapped(
        RegExp(r'(?<!<pre><code>)(\n)(?!<\/code><\/pre>)'),
        (match) => '\n',
      )
      // 保证代码块中的 \n 保留为实际换行符
      .replaceAllMapped(
        RegExp(r'(<pre><code>)(.*?)(<\/code><\/pre>)', dotAll: true),
        (match) {
          final codeContent = match.group(2) ?? '';
          return '<pre><code>${codeContent}</code></pre>';
        },
      );
  }

  void _onTapDown(TapDownDetails details) {
    PageMenuOverlay.setTapPosition(details);
  }

  void _onTap(BuildContext context, AppColors theme) {
    PageMenuOverlay.show(
      theme: theme,
      context: context,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          PageMenuItem(
            icon:CupertinoIcons.captions_bubble,
            theme: theme, 
            text: "反馈", 
            onTap:  () {
              PageMenuOverlay.hide();
            }
          ),
          PageMenuItem(
            icon:CupertinoIcons.share,
            theme: theme ,
            text:  "分享",
            onTap:  () {
              final qrParams = {
                "id":widget.questionDetail.id,
                "ids":widget.ids,
                "typeId":widget.typeId,
                "views":widget.questionDetail.views.value,
                "tab":widget.tab
              };
              PageMenuOverlay.hide();
              ShareOverlay.show(
                context: context, 
                theme: theme,
                qrString: jsonEncode(qrParams),
                title:widget.questionDetail.stem
              );
            }
          ),
        ],
      ),
    );
  }


  Future <void> questionOpt (String type ) async {
    final isLike = type == "like";
    // 根据type动态获取标志位
    final flagNotifier = isLike ? widget.questionDetail.likeFlag: widget.questionDetail.collectFlag;
    //  更新标志位（乐观更新）
    flagNotifier.value = flagNotifier.value == 0 ? 1 : 0;
    //  调用 controller 发送请求
    if(widget.tab!.isEmpty){
      await _questionDetailsController.toggleLikeCount(
        widget.typeId,
        widget.questionDetail.id,
        flagNotifier.value == 1 ? "add" : "cut",
        type,
      );
    }else{
      await _interviewDetailsController.toggleLikeCount(
        widget.tab!, 
        widget.questionDetail.id,
        flagNotifier.value == 1 ? "add" : "cut",
        type,
      );
    }
    
    if(!isLike){
      AppPromptOverlay.show(
        context: context, 
        message: flagNotifier.value == 0 ? "已取消收藏" :" 收藏成功，可以在收藏夹查看" , 
        position: "top", 
        durationMilliseconds: 800
      );
    }
  }



  @override
  Widget build(BuildContext context) {

    return PopScope(
      canPop: true,
      onPopInvokedWithResult:(didPop, result) {
        if(didPop){
          Logger.info("监听页面退出", tag: "PopScope");
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              children: [
                QuestionUserinfo(
                  avatar: widget.questionDetail.creatorAvatar, 
                  username: widget.questionDetail.creatorName,
                  questionStem: widget.questionDetail.stem, 
                  theme: widget.theme, 
                  difficulty:widget.questionDetail.difficulty,
                  collectFlag: widget.questionDetail.collectFlag.value,
                  onTap: _onTap, 
                  onTapDown: _onTapDown,
                  onChangeCollect:questionOpt
                ),
                SizedBox(height: 14),
                QuestionAnswer(
                  isHtmlLoaded: _isHtmlLoaded, 
                  controller: _controller
                )
              ],
            )
          )),
          QuestionFooter(
            likeFlag:widget.questionDetail.likeFlag.value,
            stages:  widget.questionDetail.stage, 
            likeCount:  widget.questionDetail.likeCount.value, 
            views:  widget.questionDetail.views.value, 
            theme: widget.theme,
            onTap: questionOpt,
          )
        ],
      ),
    );
  }
}
